package com.moyun.modelclass.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.IntRange;
import androidx.annotation.Nullable;
import androidx.core.view.WindowCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.moyun.modelclass.R;
import com.moyun.modelclass.base.BaseActivity;
import com.moyun.modelclass.dialog.NoticeDialog;
import com.moyun.modelclass.event.LoginStateEvent;
import com.moyun.modelclass.fragment.MainChatFragment;
import com.moyun.modelclass.fragment.MainHomeFragment;
import com.moyun.modelclass.fragment.MainMineFragment;
import com.moyun.modelclass.fragment.MainModelFragment;
import com.moyun.modelclass.fragment.MainShoppingFragment;
import com.moyun.modelclass.frank.HeartBeatRequest;
import com.moyun.modelclass.http.CommonConfiguration;
import com.moyun.modelclass.http.api.NoticeGetNoticeApi;
import com.moyun.modelclass.http.model.HttpData;
import com.moyun.modelclass.utils.FragmentUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * 作者：Meteor
 * 日期：2022/1/15 17:25
 * tip：主页面
 */
public class MainActivity extends BaseActivity {
    private LinearLayout llMainAll;
    private LinearLayout llMainHome;
    private ImageButton imageMainHome;
    private TextView textMainHome;

    private LinearLayout llMainModel;
    private ImageButton imageMainModel;
    private TextView textMainModel;
    private LinearLayout llMainShopping;
    private ImageButton imageMainShopping;
    private TextView textMainShopping;

    private LinearLayout llMainChat;
    private ImageButton imageMainChat;
    private TextView imageMainChatRedHot;
    private TextView textMainChat;

    private LinearLayout llMainMine;
    private ImageButton imageMainMine;
    private TextView textMainMine;

    private final Fragment[] mFragments = new Fragment[5];
    private int mCurrentIndex = 0;
    private Fragment mCurrentFragment;
    private FragmentManager mFragmentManager;
    private Bundle mSavedInstanceState;
    private ScheduledFuture<?> schedule;

    public static void start(Context context) {
        Intent starter = new Intent(context, MainActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        this.mSavedInstanceState = savedInstanceState;
        super.onCreate(savedInstanceState);
        if (!ImmersionBar.hasNavigationBar(this)){
            WindowCompat.setDecorFitsSystemWindows(this.getWindow(), false);
            this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            this.getWindow().setNavigationBarColor(Color.TRANSPARENT);
        }
    }


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    @SuppressLint("CutPasteId")
    @Override
    protected void assignViews() {
        llMainAll = (LinearLayout) findViewById(R.id.ll_main_all);
        llMainHome = (LinearLayout) findViewById(R.id.ll_main_home);
        imageMainHome = (ImageButton) findViewById(R.id.image_main_home);
        textMainHome = (TextView) findViewById(R.id.text_main_home);

        llMainModel = (LinearLayout) findViewById(R.id.ll_main_model);
        imageMainModel = (ImageButton) findViewById(R.id.image_main_model);
        textMainModel = (TextView) findViewById(R.id.text_main_model);

        llMainShopping = (LinearLayout) findViewById(R.id.ll_main_shopping);
        imageMainShopping = (ImageButton) findViewById(R.id.image_main_shopping);
        textMainShopping = (TextView) findViewById(R.id.text_main_shopping);

        llMainChat = (LinearLayout) findViewById(R.id.ll_main_chat);
        imageMainChat = (ImageButton) findViewById(R.id.image_main_chat);
        imageMainChatRedHot = (TextView) findViewById(R.id.image_main_chat_red_hot);
        textMainChat = (TextView) findViewById(R.id.text_main_chat);

        llMainMine = (LinearLayout) findViewById(R.id.ll_main_mine);
        imageMainMine = (ImageButton) findViewById(R.id.image_main_mine);
        textMainMine = (TextView) findViewById(R.id.text_main_mine);

        mFragmentManager = getSupportFragmentManager();
        if (mSavedInstanceState != null) {
//            mCurrentIndex = mSavedInstanceState.getInt(KEY_SELECT_INDEX, 0);
            releaseFragment();
        }

        mFragments[0] = new MainHomeFragment();
        mFragments[1] = new MainModelFragment();
        mFragments[2] = new MainShoppingFragment();
        mFragments[3] = new MainChatFragment();
        mFragments[4] = new MainMineFragment();

        imageMainHome.setSelected(true);
        textMainHome.setEnabled(true);

        imageMainModel.setSelected(false);
        textMainModel.setEnabled(false);

        imageMainShopping.setSelected(false);
        textMainShopping.setEnabled(false);

        imageMainChat.setSelected(false);
        textMainChat.setEnabled(false);

        imageMainMine.setSelected(false);
        textMainMine.setEnabled(false);
        doOnTabSelected(mCurrentIndex);

        if (ImmersionBar.hasNavigationBar(this)) {
            LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) llMainAll.getLayoutParams();
            linearParams.height = SizeUtils.dp2px(56);
            llMainAll.setLayoutParams(linearParams);
        }else {
            LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) llMainAll.getLayoutParams();
            linearParams.height = SizeUtils.dp2px(76);
            llMainAll.setLayoutParams(linearParams);
            llMainAll.setPadding(0,0,0,SizeUtils.dp2px(20));
        }
    }

    @Override
    protected void registerListeners() {
        ClickUtils.applySingleDebouncing(llMainHome, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageMainHome.setSelected(true);
                textMainHome.setEnabled(true);

                imageMainModel.setSelected(false);
                textMainModel.setEnabled(false);

                imageMainShopping.setSelected(false);
                textMainShopping.setEnabled(false);

                imageMainChat.setSelected(false);
                textMainChat.setEnabled(false);

                imageMainMine.setSelected(false);
                textMainMine.setEnabled(false);
                doOnTabSelected(0);
            }
        });

        ClickUtils.applySingleDebouncing(llMainModel, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageMainHome.setSelected(false);
                textMainHome.setEnabled(false);

                imageMainModel.setSelected(true);
                textMainModel.setEnabled(true);

                imageMainShopping.setSelected(false);
                textMainShopping.setEnabled(false);

                imageMainChat.setSelected(false);
                textMainChat.setEnabled(false);

                imageMainMine.setSelected(false);
                textMainMine.setEnabled(false);
                doOnTabSelected(1);
            }
        });

        ClickUtils.applySingleDebouncing(llMainShopping, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (CommonConfiguration.isLogin(kv)) {
                    imageMainHome.setSelected(false);
                    textMainHome.setEnabled(false);

                    imageMainModel.setSelected(false);
                    textMainModel.setEnabled(false);

                    imageMainShopping.setSelected(true);
                    textMainShopping.setEnabled(true);

                    imageMainChat.setSelected(false);
                    textMainChat.setEnabled(false);

                    imageMainMine.setSelected(false);
                    textMainMine.setEnabled(false);
                    doOnTabSelected(2);
                } else {
                    LoginVerificationCodeActivity.start(MainActivity.this);
                }
            }
        });

        ClickUtils.applySingleDebouncing(llMainChat, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (CommonConfiguration.isLogin(kv)) {
                    imageMainHome.setSelected(false);
                    textMainHome.setEnabled(false);

                    imageMainModel.setSelected(false);
                    textMainModel.setEnabled(false);

                    imageMainShopping.setSelected(false);
                    textMainShopping.setEnabled(false);

                    imageMainChat.setSelected(true);
                    textMainChat.setEnabled(true);

                    imageMainMine.setSelected(false);
                    textMainMine.setEnabled(false);
                    doOnTabSelected(3);
                } else {
                    LoginVerificationCodeActivity.start(MainActivity.this);
                }
            }
        });

        ClickUtils.applySingleDebouncing(llMainMine, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageMainHome.setSelected(false);
                textMainHome.setEnabled(false);

                imageMainModel.setSelected(false);
                textMainModel.setEnabled(false);

                imageMainShopping.setSelected(false);
                textMainShopping.setEnabled(false);

                imageMainChat.setSelected(false);
                textMainChat.setEnabled(false);

                imageMainMine.setSelected(true);
                textMainMine.setEnabled(true);
                doOnTabSelected(4);
            }
        });
    }

    @Override
    protected void getExtras(Bundle bundle) {

    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void doAction() {
        if (getIntent() != null) {
            Intent intent = getIntent();
            String action = intent.getAction();
            String type = null;
            String id = null;
            if (Intent.ACTION_VIEW.equals(action)) {
                Uri uri = intent.getData();
                if (uri != null) {
                    type = uri.getQueryParameter("type");
                    id = uri.getQueryParameter("id ");
                }
            }
        }
        initNoticeGetNotice();
        if (CommonConfiguration.isLogin(kv)) {
            startBeat();
        }
    }

    //移除fragment，避免出现fragment重叠的问题
    private void releaseFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        for (Fragment f : fragments) {
            if (f != null) {
                transaction.detach(f);
                transaction.remove(f);
            }
        }
        transaction.commitNowAllowingStateLoss();
    }

    public void setTabSelect(int position) {
        imageMainHome.setSelected(false);
        textMainHome.setEnabled(false);

        imageMainModel.setSelected(false);
        textMainModel.setEnabled(false);

        imageMainShopping.setSelected(false);
        textMainShopping.setEnabled(false);

        imageMainChat.setSelected(false);
        textMainChat.setEnabled(false);

        imageMainMine.setSelected(false);
        textMainMine.setEnabled(false);
        switch (position) {
            case 0:
                imageMainHome.setSelected(true);
                textMainHome.setEnabled(true);
                break;
            case 1:
                imageMainModel.setSelected(true);
                textMainModel.setEnabled(true);
                break;
            case 2:
                imageMainShopping.setSelected(true);
                textMainShopping.setEnabled(true);
                break;
            case 3:
                imageMainChat.setSelected(true);
                textMainChat.setEnabled(true);
                break;
            case 4:
                imageMainMine.setSelected(true);
                textMainMine.setEnabled(true);
                break;
        }
        doOnTabSelected(position);
    }

    private void doOnTabSelected(@IntRange(from = 0, to = 4) int position) {
        mCurrentFragment = FragmentUtils.switchContent(mFragmentManager, mCurrentFragment, mFragments[position], R.id.main_frame, position, false);
        mCurrentIndex = position;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginStatEvent(LoginStateEvent event) {
        Log.d(TAG, "onLoginStatEvent() called with: event = [" + event + "]");
        if (event.getState() == 1) {
            startBeat();
        } else {
            stopBeat();
        }
    }

    public void stopBeat() {
        EasyHttp.cancel("heartBeatRequest");
        unreadMsgSet.clear();
        if (schedule != null) {
            schedule.cancel(true);
            schedule = null;
        }
    }

    public void startBeat() {
        EasyHttp.post(this)
                .api(new HeartBeatRequest())
                .tag("heartBeatRequest")
                .request(new HttpCallback<HttpData<HeartBeatRequest.Bean>>(null) {
                    @Override
                    public void onSucceed(HttpData<HeartBeatRequest.Bean> result) {
                        if (result != null) {
                            if (result.getCode() == 1) {
                                HeartBeatRequest.Bean bean = result.getData();
                                if (bean == null) {
                                    return;
                                }
                                unreadMsgSet.clear();
                                Log.d(TAG, "onSuccess() called with: bean = [" + bean + "]");
                                if (bean.newChat != null && bean.newChat.size() > 0) {
                                    for (HeartBeatRequest.NewChat newChat : bean.newChat) {
                                        unreadMsgSet.put(newChat.userId, newChat.unreadCount);
                                    }
                                }
                                if (unreadMsgSet.isEmpty()) {
                                    imageMainChatRedHot.setVisibility(View.INVISIBLE);
                                } else {
                                    int c = 0;
                                    for (Integer value : unreadMsgSet.values()) {
                                        c += value;
                                    }
                                    imageMainChatRedHot.setText(String.valueOf(c));
                                    imageMainChatRedHot.setVisibility(View.VISIBLE);
                                }
                                List<HeartBeatRequest.NewChat> newChat = bean.newChat;
                                if (newChat != null && newChat.size() > 0) {
                                    EventBus.getDefault().post(bean.newChat);
                                }
                                long nextExecuteSecond = (long) bean.nextExecuteSecond;
                                if (schedule != null) {
                                    schedule.cancel(true);
                                    schedule = null;
                                }
                                schedule = Executors.newSingleThreadScheduledExecutor().schedule(new Runnable() {
                                    @Override
                                    public void run() {
                                        startBeat();
                                    }
                                }, nextExecuteSecond, TimeUnit.SECONDS);
                            } else {
                            }
                        } else {
                        }
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume() called" + unreadMsgSet);
        if (unreadMsgSet.isEmpty()) {
            imageMainChatRedHot.setVisibility(View.INVISIBLE);
        } else {
            int c = 0;
            for (Integer value : unreadMsgSet.values()) {
                c += value;
            }
            imageMainChatRedHot.setText(String.valueOf(c));
            imageMainChatRedHot.setVisibility(View.VISIBLE);
        }
    }

    public static final Map<String, Integer> unreadMsgSet = new HashMap<>();
    private static final String TAG = "MainActivity";

    private void initNoticeGetNotice() {
        EasyHttp.post(this)
                .api(new NoticeGetNoticeApi())
                .request(new HttpCallback<HttpData<NoticeGetNoticeApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<NoticeGetNoticeApi.Bean> result) {
                        if (result != null && result.getData() != null) {
                            NoticeDialog.getInstance(MainActivity.this,
                                    CommonConfiguration.splitResUrlTwo(result.getData().getImage()),
                                    result.getData().getUrl()).builder().setNegativeButton().show();
                        }
                    }
                });
    }
}
